<template>
  <div>
    <modal-view :loading="singLoading" title="门店详情" ref="modalViewRef" width="800px" :before-submit="beforeSubmit" @close="close">
      <el-form ref="formRef" label-width="80px" :model="formData" :rules="rules" label-position="left" size="small">
        <el-tabs>
          <el-tab-pane label="基本设置">
            <div class="page-tabbody">
              <div class="page-header">
                <div class="page-header-left ">
                  <upload-img size="130px" :doc-type="docType" v-model="formData._logo">
                  </upload-img>
                </div>
                <div class="page-header-right">
                  <el-form-item label="编号">
                    <el-input v-model="formData.Id" placeholder="自动生成" disabled></el-input>
                  </el-form-item>
                  <el-form-item label="门店名称" prop="Name">
                    <el-input v-model="formData.Name"></el-input>
                  </el-form-item>
                  <el-form-item label="联系方式" prop="Phone">
                    <el-input v-model="formData.Phone"></el-input>
                  </el-form-item>
                </div>
              </div>
              <!-- <el-divider content-position="left">位置信息</el-divider> -->
            </div>
          </el-tab-pane>
          <el-tab-pane label="地理位置">
            <div class="page-tabbody">
              <!-- 地图选择 -->
              <div class="page-map">
                <div class="page-map-left">
                  <el-select v-model="mapValue" style="width:100%;margin-bottom: 10px;" filterable remote reserve-keyword
                    placeholder="搜索门店位置" :remote-method="remoteMethod" :loading="mapLoading" @change="onChange">
                    <el-option v-for="item in options" :key="item.id" :label="item.title" :value="item">
                      <div class="page-option">
                        <div class="page-option-header">
                          <div>{{ item.title }}</div>
                          <div class="page-option-header-line">{{ item.line }}</div>
                        </div>
                      </div>
                    </el-option>
                  </el-select>
                  <div class="page-map-dom" ref="mapDom">
                  </div>
                </div>
                <div class="page-map-right">
                  <el-form-item label="详细地址" prop="Address">
                    <el-input type="textarea" v-model="formData.Address"
                      :autosize="{ minRows: 5, maxRows: 5 }"></el-input>
                  </el-form-item>
                  <el-form-item label="城市" prop="City">
                    <el-input v-model="formData.City" disabled></el-input>
                  </el-form-item>
                  <el-form-item label="经度" prop="Longitude">
                    <el-input v-model="formData.Longitude" disabled></el-input>
                  </el-form-item>
                  <el-form-item label="纬度" prop="Latitude">
                    <el-input v-model="formData.Latitude" disabled></el-input>
                  </el-form-item>
                </div>
              </div>
            </div>
          </el-tab-pane>
          <el-tab-pane label="轮播图">
            <div class="page-tabbody">
              <div style="margin-bottom: 10px;">*轮播图请使用 4:3 比例图片</div>
              <upload-img-list ref="uploadImgListRef" :doc-type="docType">
              </upload-img-list>
            </div>
          </el-tab-pane>
          <el-tab-pane label="首页介绍">
            <div class="page-tabbody">
              <wangeditor-vue v-model="formData.Project" :doc-type="docType">
              </wangeditor-vue>
            </div>
          </el-tab-pane>
        </el-tabs>
      </el-form>
    </modal-view>
  </div>
</template>

<script lang="ts">
import { defineComponent } from "vue";
import { IS_DEVE } from "@/config";
import { queryGet } from "@/utils/api";
export default defineComponent({
  name: "CmpModalView",
})
</script>

<script lang="ts" setup>
import { ref, reactive, nextTick } from "vue";
import { ElMessage } from "element-plus";
import ModalView from "@/components/ModalView";
import { appAction } from "@/store/app";
import { docType, CmpDataClass } from "@/model/Cmp";
import { request } from "@/utils/axios";
import { onMapInit, mapKey } from "@/utils/map";
import { UploadImg, UploadImgList } from "@/components/UploadFile";
import WangeditorVue from "@/components/WangeditorVue";

import axios from 'axios';

let emit = defineEmits<{
  (e: "close"): void;
  (e: "submit", value: CmpDataClass): void
}>()

/**
 * 弹框
 */
let modalViewRef = ref();

/**
 * 表单
 */
let formRef = ref();

/**
 * 图片列表
 */
let uploadImgListRef = ref();

/**
 * 子表loading
 */
let singLoading = ref(false);

/**
 * 表单
 */
let formData = ref<CmpDataClass>(new CmpDataClass({}));

/**
 * 表单验证
 */
let rules = reactive({
  Name: [{ required: true, message: '当前项为必填项', trigger: 'blur' }],
  Phone: [{ required: true, message: '当前项为必填项', trigger: 'blur' }],
  Address: [{ required: true, message: '当前项为必填项', trigger: 'blur' }],
  City: [{ required: true, message: '当前项为必填项', trigger: 'blur' }],
  Longitude: [{ required: true, message: '当前项为必填项', trigger: 'blur' }],
  Latitude: [{ required: true, message: '当前项为必填项', trigger: 'blur' }],
})

/**
 * 页面展示
 */
function show(data?: any) {
  formData.value = new CmpDataClass(data || {});
  /**
   * 打开页面
   */
  modalViewRef.value.show();

  if (formData.value.Id) {
    //更新 , 获取子表数据
    getSingeData()
  }

  nextTick(() => {
    mapInit();
  })
}

/**
 * 获取子表数据
 */
function getSingeData() {
  singLoading.value = true;
  Promise.all([
    queryGet({
      docType: "CmpBanner",
      apiType: "SingleList"
    }, {
      Id: formData.value.Id
    }),
    queryGet({
      docType: "CmpProject",
      apiType: "Single"
    }, {
      Id: formData.value.Id
    })
  ])
    .then((resList) => {
      formData.value.Project = resList[1].Content || "";
      let imgList = resList[0];
      nextTick(() => {
        uploadImgListRef.value.setImgList(imgList.map((item: any) => item.Img))
      })
    })
    .finally(() => {
      singLoading.value = false;
    })
}

/**
 *  保存前校验
 */
function beforeSubmit(): Promise<void> {
  return new Promise((resolve, reject) => {
    formRef.value.validate()
      .then(() => {

        let url = "";
        if (formData.value.Id) {
          //存在为修改
          url = "/" + docType + "/Update";
        } else {
          //不存在ID 为更新
          url = "/" + docType + "/Add";
        }
        //获取banner数据
        let imgList: string[] = uploadImgListRef.value.getImgList();
        //数据提交
        request(url, Object.assign({}, formData.value, {
          Banners: imgList.map(item => {
            return {
              Img: item
            }
          })
        }))
          .then(() => {
            ElMessage.success("表单数据保存成功");
            emit("submit", formData.value);
            resolve();
          })
          .catch(() => {
            appAction.resetPageuuid();
            reject();
          })
      })
      .catch(reject)
  })
}

/**
 * 关闭页面
 */
function close() {
  emit("close")
}

/**
 * 导出
 */
defineExpose({
  show
})

/**
 * ====================
 *  地图相关
 * ====================
 */

let mapDom = ref(null);

/**
 * map搜索框
 */
let mapValue = ref("");

/**
 * 搜索loading
 */
let mapLoading = ref(false);

let options = ref<{
  id: string,
  title: string,
  adder: string,
  line: string,
  lat: number,
  lng: number,
  city: string
}[]>([])

let mapqq: any;

/**
 * 标记物
 */
let marker: any

/**
 * 全程测试
 */
function remoteMethod(query: string) {
  if (query) {
    mapLoading.value = true;
    request(`/Map/QqSuggestion`, {
      keyword: query
    }, {
      methods: "get"
    })
      .then(res => {
        try {
          let data = JSON.parse(res);
          if (data.status == 0) {
            options.value = [];
            for (let item of data.data) {
              options.value.push({
                id: item.id,
                title: item.title,
                adder: item.address,
                line: `${item.province}/${item.city}/${item.district}`,
                lat: item.location.lat,
                lng: item.location.lng,
                city: item.city,
              })
            }
          } else {
            options.value = []
          }
        } catch (error) {
          ElMessage.error("腾讯地图地址解析错误")
        }
      })
      .finally(() => {
        mapLoading.value = false;
      })
  } else {
    options.value = [];
  }
}

// 更新的时候
function onChange(row: any) {
  //调整地图中心点
  let tallng = new qq.maps.LatLng(row.lat, row.lng);
  mapqq.panTo(tallng);
  //移动标记物位置
  marker.setPosition(tallng);
  formData.value.City = row.city;
  formData.value.Longitude = row.lng;
  formData.value.Latitude = row.lat;
  formData.value.Address = row.adder;
}

/**
 * 地图初始化
 */
function mapInit() {
  onMapInit(() => {
    mapqq = new qq.maps.Map(mapDom.value, {
      center: new qq.maps.LatLng(formData.value.Latitude || 39.916527, formData.value.Longitude || 116.397128),      // 地图的中心地理坐标。
      zoom: 12 // 地图的中心地理坐标。
    });
    marker = new qq.maps.Marker({
      position: new qq.maps.LatLng(formData.value.Latitude || 39.916527, formData.value.Longitude || 116.397128),
      map: mapqq
    });
    //添加监听事件  获取鼠标点击事件
    qq.maps.event.addListener(mapqq, 'click', function (event: any) {
      marker.setPosition(event.latLng);
      formData.value.Longitude = event.latLng.lng;
      formData.value.Latitude = event.latLng.lat;
    });
  })
}

/**
 * ====================
 *  页面初始化
 * ====================
 */


</script>

<style lang="less" scoped>
.page-tabbody {
  height: 400px;
}

.page-header {
  display: flex;
}

.page-header-left {
  flex-shrink: 0;
  margin-right: 20px;
}

.page-header-right {
  flex-grow: 1;
}

.page-map {
  display: flex;
}

.page-map-left {
  flex-shrink: 0;
  flex-basis: 350px;
  margin-right: 20px;
}

.page-map-right {
  flex-grow: 1;
}

.page-map-dom {
  width: 350px;
  height: 350px;
}


.page-option {
  color: black;
}

.page-option-header {
  display: flex;
}

.page-option-header-line {
  color: rgba(0, 0, 0, 0.5);
  margin-left: 10px;
}
</style>